import { defineStore } from 'pinia';
import { MedicalDocument } from '../types/medicalTypes';

export const useEditorStore = defineStore('editor', {
  state: () => ({
    editorValue: [] as MedicalDocument,
    config: {
        language: 'zh-CN',
        defaultFontFamily: 'SimSun',
        defaultFontSize: 14,  // Add this property
        fontSize: 14,         // Add this property
        fontFamily: 'SimSun',         // Add this property
        enableUndoRedo: true,
        enableAutoSave: true,
        autoSaveInterval: 30000,
        maxUndoSteps: 100,
        medical: {
          enableTermSuggestion: true,
          enableSectionValidation: true,
          requiredSections: ['chief-complaint', 'present-illness', 'diagnosis']
        }
      },
    currentFilePath: null as string | null,
    isDocumentModified: false,
    undoStack: [] as MedicalDocument[],
    redoStack: [] as MedicalDocument[]
  }),
  
  actions: {
    setEditorValue(value: MedicalDocument) {
      if (!value) {
        throw new Error('Editor value cannot be null or undefined');
      }
      
      // Update this line to use the config property directly
      if (this.undoStack.length > this.config.maxUndoSteps) {
        this.undoStack.shift();
      }
      this.undoStack.push([...this.editorValue]);
      
      // 清空重做栈
      this.redoStack = [];
      
      // 更新值
      this.editorValue = value;
      this.isDocumentModified = true;
    },
    
    undo() {
      if (this.undoStack.length === 0) {
        console.warn('No more undo steps available');
        return;
      }
      // 保存当前状态到重做栈
      this.redoStack.push([...this.editorValue]);
      
      // 恢复上一个状态
      this.editorValue = this.undoStack.pop() || [];
      this.isDocumentModified = true;
    },
    
    redo() {
      if (this.redoStack.length === 0) {
        console.warn('No more redo steps available'); 
        return;
      }
      // 保存当前状态到撤销栈
      this.undoStack.push([...this.editorValue]);
      
      // 恢复下一个状态
      this.editorValue = this.redoStack.pop() || [];
      this.isDocumentModified = true;
    },
    
    setConfig(config: Partial<typeof this.config>) {
      this.config = { ...this.config, ...config };
    },
    
    saveDocument(filePath: string) {
      // 实际项目中会实现文件保存逻辑
      this.currentFilePath = filePath;
      this.isDocumentModified = false;
    },
    
    loadDocument(content: MedicalDocument, filePath: string) {
      this.editorValue = content;
      this.currentFilePath = filePath;
      this.isDocumentModified = false;
      this.undoStack = [];
      this.redoStack = [];
    }
  }
});